class FriendModel {
  final int id;
  final int userId;
  final String username;
  final String? nickname;
  final String? avatar;
  final String? remark;
  final String? openId; // open_id 用于消息匹配
  final int status; // 好友状态：0-待确认，1-已同意，2-已拒绝，3-已拉黑
  final DateTime? createdAt;

  FriendModel({
    required this.id,
    required this.userId,
    required this.username,
    this.nickname,
    this.avatar,
    this.remark,
    this.openId,
    required this.status,
    this.createdAt,
  });

  factory FriendModel.fromJson(Map<String, dynamic> json) {
    // 处理嵌套的 user 对象（后端返回格式）
    String username = '';
    int userId = 0;
    String? nickname;
    String? avatar;
    
    String? openId;
    
    if (json['user'] != null && json['user'] is Map<String, dynamic>) {
      final user = json['user'] as Map<String, dynamic>;
      // 从 user 对象中获取用户信息
      username = user['name']?.toString() ?? 
                 user['user_name']?.toString() ?? 
                 user['username']?.toString() ?? 
                 '';
      userId = user['id'] is int 
          ? user['id'] as int
          : int.tryParse(user['id']?.toString() ?? '0') ?? 0;
      nickname = user['nickname']?.toString();
      avatar = user['file_name']?.toString() ?? user['avatar']?.toString();
      openId = user['open_id']?.toString();
    } else {
      // 如果没有嵌套 user 对象，直接从根对象获取
      username = json['username']?.toString() ?? 
                 json['user_name']?.toString() ?? 
                 json['name']?.toString() ?? 
                 '';
      userId = json['user_id'] is int
          ? json['user_id'] as int
          : json['id'] is int
              ? json['id'] as int
              : int.tryParse(json['user_id']?.toString() ?? json['id']?.toString() ?? '0') ?? 0;
      nickname = json['nickname']?.toString();
      avatar = json['avatar']?.toString();
      openId = json['open_id']?.toString();
    }
    
    // 处理时间字段
    DateTime? createdAt;
    if (json['create_time'] != null) {
      try {
        final timestamp = json['create_time'] is int 
            ? json['create_time'] as int
            : int.tryParse(json['create_time'].toString());
        if (timestamp != null) {
          createdAt = DateTime.fromMillisecondsSinceEpoch(timestamp);
        }
      } catch (e) {
        // 解析失败，忽略
      }
    } else if (json['created_at'] != null) {
      try {
        createdAt = DateTime.parse(json['created_at'].toString());
      } catch (e) {
        // 解析失败，忽略
      }
    }
    
    return FriendModel(
      id: json['id'] is int 
          ? json['id'] as int
          : int.tryParse(json['id']?.toString() ?? '0') ?? 0,
      userId: userId,
      username: username,
      nickname: nickname,
      avatar: avatar,
      remark: json['remark']?.toString(),
      openId: openId,
      status: json['status'] is int 
          ? json['status'] as int
          : int.tryParse(json['status']?.toString() ?? '1') ?? 1,
      createdAt: createdAt,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'user_id': userId,
      'username': username,
      'nickname': nickname,
      'avatar': avatar,
      'remark': remark,
      'open_id': openId,
      'status': status,
      'created_at': createdAt?.toIso8601String(),
    };
  }

  String get displayName => remark ?? nickname ?? username;
}

